package rabbit_zap

import (
	"context"
	"github.com/isayme/go-amqp-reconnect/rabbitmq"
	"github.com/pkg/errors"
	"github.com/streadway/amqp"
)

var contentTypeJson = "application/json"

type RabbitMqWriter struct {
	Publisher *Publisher
}

func CreateByConfig(config *LoggerCollectorConfig) (*RabbitMqWriter, error) {
	if config == nil {
		return nil, errors.New("配置信息不能为空")
	}
	connection, err := rabbitmq.Dial(config.Amqp.GetUrl())
	if err != nil {
		return nil, err
	}
	pub, err := NewPublisher(connection, config.Amqp.Exchange, false, false)
	if err != nil {
		return nil, err
	}
	return &RabbitMqWriter{
		Publisher: pub,
	}, nil
}

func (r *RabbitMqWriter) Write(p []byte) (n int, err error) {

	pub := &amqp.Publishing{
		Headers:      make(map[string]interface{}, 0),
		ContentType:  contentTypeJson,
		DeliveryMode: amqp.Persistent,
		Body:         p,
	}
	err = r.Publisher.Publish(context.Background(), "", pub)
	if err != nil {
		return 0, err
	}

	return len(p), nil
}
